package cn.sfa.controller.manage;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.sfa.common.pagination.Pagination;
import cn.sfa.common.utils.CommonUtil;
import cn.sfa.common.utils.DeleteRepeatIds;
import cn.sfa.common.utils.WebInitBinderContoller;
import cn.sfa.common.utils.WordFilterUtil;
import cn.sfa.entity.smsmessage.SaleSmsMessage;
import cn.sfa.service.smsmessage.SmsmessageSerive;

/**
 * 消息发送
 * 
 * @author hui
 * 
 */
@Controller
@RequestMapping("sms/index")
public class ManageSmsMessageController extends WebInitBinderContoller {
	Logger log = LoggerFactory.getLogger(ManageSmsMessageController.class);
	@Autowired
	private SmsmessageSerive smsmessageSerive;

	/**
	 * 进入首页
	 * 
	 * @param smscontext
	 * @param recvmobileno
	 * @param currentPage
	 * @param request
	 * @param map
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/message")
	public String Message(

			@RequestParam(value = "recvcustomerid", required = false) String recvcustomerid,
			@RequestParam(value = "senddate", required = false) String senddate,// 时间
			@RequestParam(value = "recvmobileno", required = false) String recvmobileno,// 手机号码
			@RequestParam(value = "currentPage", required = false) String currentPage,// 页码
			HttpServletRequest request, ModelMap map,
			HttpServletResponse response) throws IOException {
		 
		int pageIndex;
		try {
			pageIndex = Integer.valueOf(currentPage);
		} catch (Exception ex) {
			pageIndex = 1;
		}
		String url = request.getContextPath() + "/sms/index?"
				+ "recvcustomerid=" + CommonUtil.jugeAndFixNull(recvcustomerid)
				+ "&senddate=" + CommonUtil.jugeAndFixNull(senddate)
				+ "&recvmobileno=" + CommonUtil.jugeAndFixNull(recvmobileno);

		Pagination pagination = smsmessageSerive.SeachMessage(pageIndex, 10,
				url, recvmobileno, recvcustomerid, senddate);
		map.put("pagination", pagination);
		map.put("recvcustomerid", recvcustomerid);
		map.put("senddate", senddate);
		map.put("recvmobileno", recvmobileno);
		return "/manage/message/index";

	}

	/**
	 * 进入发送的方法
	 * 
	 * @param saleSmsMassage
	 * @param request
	 * @param map
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/sendmessage")
	public String sendMessage(SaleSmsMessage saleSmsMassage,
			HttpServletRequest request, ModelMap map,
			HttpServletResponse response) throws IOException {

		return "/manage/message/onetomore";
	}

	/**
	 * 验证信息内容
	 * 
	 * @param saleSmsMassage
	 * @param request
	 * @param map
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/validate")
	public void validate(HttpServletRequest request, ModelMap map,
			HttpServletResponse response) throws Exception {
		String smscontext = request.getParameter("smscontext");
		String filterContext = "";
		try{ 
		filterContext = WordFilterUtil.filterText(smscontext, '*')
				.getFilteredContent();
		}catch (Exception e) {
			e.printStackTrace();
		}
		int count = 0;
		String context = "";
		String timecontext = "";
		// 验证短信内容
		if (CommonUtil.isEmpty(smscontext)) {
			context = "  报名开始时间必须大于当前系统时间! ";
			count = count + 1;
		}  
		PrintWriter out = response.getWriter();
		boolean result = count == 0;
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		request.setCharacterEncoding("UTF-8");
		JSONObject temp = new JSONObject();
		temp.put("filterContext", filterContext);
		temp.put("result", result);
		temp.put("context", context);
		temp.put("timecontext", timecontext);
		out.print(temp.toString());
		out.flush();
		out.close();
	}

	/**
	 * 验证手机
	 * 
	 * @param saleSmsMassage
	 * @param request
	 * @param map
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/validateno")
	public String validateNo(SaleSmsMessage saleSmsMassage,
			HttpServletRequest request, ModelMap map,
			HttpServletResponse response) throws Exception {
		String[] recvmobilephone = saleSmsMassage.getRecvmobileno().split("\n");
		int count = 0;
		// 得到手机号码
		String recvmobileno = "";
		if (CommonUtil.isEmpty(saleSmsMassage.getRecvmobileno())) {
			recvmobileno = "手机号码不能为空！";
			count = count + 1;
		}
		// 截取手机号码

		List<String> succeed = new ArrayList<String>();
		List<String> fail = new ArrayList<String>();
		for (int i = 0; i < recvmobilephone.length; i++) {
			if (recvmobilephone[i].length() != 11
					&& recvmobilephone[i].indexOf(1) != 1) {
				fail.add(recvmobilephone[i]);
			} else {
				succeed.add(recvmobilephone[i]);
			}
		}
		// 过滤相同的手机号码
		succeed = DeleteRepeatIds.removeDuplicateWithOrder(succeed);
		String[] succeedout = (String[]) succeed.toArray(new String[succeed
				.size()]);
		List<String> succeedback = new ArrayList<String>();
		List<String> succeedcut = new ArrayList<String>();
		int number = succeedout.length;
		// 必须正确的大于10
		if (number > 10) {
			// 得到前10条
			for (int i = 0; i < 10; i++) {
				succeedcut.add(succeedout[i]);
			}
			// 后10条
			for (int i = 9; i > 0; i--) {
				succeedback.add(succeedout[succeedout.length - i]);
			}
		}

		boolean result = count == 0;
		PrintWriter out = response.getWriter();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		request.setCharacterEncoding("UTF-8");

		JSONObject temp = new JSONObject();

		temp.put("number", number);
		temp.put("succeedcut", succeedcut);
		temp.put("succeedback", succeedback);
		temp.put("succeed", succeed);
		temp.put("fail", fail);
		temp.put("failsize", fail.size());
		temp.put("result", result);
		temp.put("recvmobileno", recvmobileno);
		temp.put("smscontext", saleSmsMassage.getSmscontext());
		out.print(temp.toString());
		out.flush();
		out.close();

		return "/manage/message/onetomore";
	}

	/**
	 * 输入号码，内容的方法
	 * 
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping("/intoexcel")
	public String intoexcel(HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {

		return "/manage/message/intoexcel";
	}

	/**
	 * 得到内容进行解析
	 * 
	 * @param recvmobileno
	 * @param model
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/info")
	public String succeedinfo(
			@RequestParam(value = "recvmobileno", required = false) String recvmobileno,// 信息内容
			@RequestParam(value = "validdatetime", required = false) String validdatetime,// 有效时间
			SaleSmsMessage model, HttpServletRequest request,
			HttpServletResponse response, ModelMap map) throws IOException {
		// 第一次截取 并过滤词
		String[] result = WordFilterUtil.filterText(recvmobileno, '*')
				.getFilteredContent().split("\r\n");
		String[][] info = new String[result.length][];
		// 第二次截取 截取空格
		for (int i = 0; i < result.length; i++) {
			info[i] = result[i].split("\t");// 用tab来截取
		}

		String succeedStr = "";
		List<List<String>> succeedDime = new ArrayList<List<String>>();
		List<List<String>> failDime = new ArrayList<List<String>>();
		 

		// 验证失败成功的条目
		for (int i = 0; i < info.length; i++) {

			if (info[i][1].length() != 11 || info[i][1].indexOf("1") != 0 || info[i].length < 3) {
				List<String> fail = new ArrayList<String>();
				for (int j = 0; j < info[i].length; j++) { 
					fail.add(info[i][j]);
				} 
				failDime.add(fail);
				
			} else {

				List<String> succeed = new ArrayList<String>();
				for (int j = 0; j < info[i].length; j++) {
					succeedStr += info[i][j] + "&---&";
					succeed.add(info[i][j]);
				}
				succeedStr += "-&&&-";
				succeedDime.add(succeed);
			}

		}

		map.put("succeedStr", succeedStr);
		map.put("succeedDime", succeedDime); 
		map.put("succeedSize", succeedDime.size());
		map.put("failDime", failDime); 
		map.put("failSize", failDime.size());

		map.put("lastBegin", succeedDime.size()-5);
		map.put("lastEnd", succeedDime.size()-1);	
		map.put("validdatetime", validdatetime);
		return "/manage/message/moretomore";
	}

	/*
	 * 不同手机号码发送不同的内容
	 */
	@RequestMapping("/add")
	public void addmessage(
			@RequestParam(value = "succeedStr", required = false) String succeedStr,// 信息内容
			@RequestParam(value = "validdatetime", required = false) String validdatetime,// 有效时间
			SaleSmsMessage model, HttpServletRequest request,
			HttpServletResponse response, ModelMap map)
			throws Exception {
			String succeed[] = succeedStr.split("-&&&-");
			String[][] info = new String[succeed.length][];
			List<List<String>> succeedDime = new ArrayList<List<String>>(); 
			for (int i = 0; i < succeed.length; i++) {
				info[i]= succeed[i].split("&---&");
			}	
			smsmessageSerive.insertsmsmessage(info, validdatetime, model);
	}
	/**
	 * 多个号码发送同一个内容
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/onetomore")
	public String onetomore(SaleSmsMessage model, HttpServletRequest request,
			HttpServletResponse response, ModelMap map) throws Exception {
		String context = request.getParameter("context");
		String sendsucceed = request.getParameter("sendsucceed");
		String validdatetimes = request.getParameter("validdatetimes");
		// 截去头和尾
		validdatetimes = validdatetimes.substring(1,
				validdatetimes.length() - 1);
		 
		sendsucceed = sendsucceed.substring(1, sendsucceed.length() - 1);
		// 去掉，获得号码
		String[] send = sendsucceed.split(",");
		smsmessageSerive.addsmsmessage(send, model, context, validdatetimes);
		return "/manage/message/index";
	}

	/*
	 * 选择模式
	 */
	@RequestMapping("/send")
	public String send(SaleSmsMessage model, HttpServletRequest request,
			HttpServletResponse response, ModelMap map) {
		return "/manage/message/send";
	}
}
